<template>
  <div class="add-judge-question">
    <!-- 题目类型选择 -->
    <div class="form-group">
      <div class="type-section-row">
        <div class="type-select-group">
          <label class="form-label">题目类型:</label>
          <el-select
            v-model="questionType"
            placeholder="请选择题目类型"
            class="question-type-select"
            @change="handleChangeQuestionType"
            :disabled="questionId && questionId !== ''"
          >
            <el-option
              v-for="item in questionTypeList"
              :key="item.type"
              :label="item.message"
              :value="item.type"
            ></el-option>
          </el-select>
        </div>
        <div class="section-select-group">
          <label class="form-label">选择知识点:</label>
          <el-cascader
            ref="questionKnowledge"
            v-model="questionKnowledge"
            :options="knowledgeList"
            :props="cascaderProps"
            placeholder="请选择知识点"
            class="question-section-select"
            clearable
          />
        </div>
      </div>
    </div>

    <!-- 试题题目 -->
    <div class="form-group">
      <label class="form-label">试题题目</label>
      <div class="editor-container">
        <MdEditor
          v-model="questionContent"
          :preview="false"
          :toolbars="toolbars"
          placeholder="开始编辑..."
          class="question-editor"
          @onHtmlChanged="onQuestionHtmlChanged"
        />
      </div>
    </div>

    <!-- 分析题答案 -->
    <div class="form-group">
      <label class="form-label">试题答案</label>
      <div class="editor-container">
        <MdEditor
          v-model="correctAnswer"
          :preview="false"
          :toolbars="toolbars"
          placeholder="开始编辑..."
          class="question-editor"
          @onHtmlChanged="onCorrectAnswerHtmlChanged"
        />
      </div>
    </div>

    <!-- 保存按钮 -->
    <div class="save-container">
      <el-button
        color="#457aff"
        primary
        @click="saveQuestion()"
        class="save-btn"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "make_addChoiceQuestion",
  data() {
    return {
      courseId: "",
      questionId: "",
      kbId: "",
      chapterId: "",
      questionType: "分析题",
      questionTypeList: [],
      questionContent: "",
      questionContentHtml: "",
      correctAnswer: "",
      correctAnswerHtml: "",
      knowledgeList: [],
      questionKnowledge: "",
      cascaderProps: {
        value: "value",
        label: "label",
        children: "children",
      },
      questionSection: "",
      questionContent: "",
      correctAnswer: "",
      toolbars: [
        "bold",
        "underline",
        "italic",
        "strikeThrough",
        "sub",
        "sup",
        "quote",
        "unorderedList",
        "orderedList",
        "task",
        "codeRow",
        "code",
        "link",
        "image",
        "table",
        "mermaid",
        "katex",
        "revoke",
        "next",
        "preview",
      ],
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.questionId = this.$route.query.rowId;
    this.kbId = this.$route.query.kbId;
    this.chapterId = this.$route.query.chapterId;
    this.getSelectData();
    this.getKnowledgeList();
    this.getQuestionData();
  },
  methods: {
    // 获取下拉数据
    getSelectData() {
      this.$axios
        .get(
          `/tes/course/${this.courseId}/businessType/1/question-repository/dropdown-list`
        )
        .then((res) => {
          this.questionTypeList = res.data.questionTypeList;
        });
    },

    // 获取知识点
    getKnowledgeList() {
      this.$axios
        .get(`/tes/course/auto/make/chapter-kb?courseId=${this.courseId}`)
        .then((res) => {
          this.knowledgeList = res.data;
        });
    },

    // 获取题目数据
    getQuestionData() {
      if (!this.questionId) {
        return;
      }
      this.$axios
        .get(
          `/tes/course/${this.courseId}/businessType/1/question-repository/question/${this.questionId}`
        )
        .then((res) => {
          this.questionContent = res.data.content;
          this.correctAnswer = res.data.answer[0].content;
          this.questionType = res.data.questionType;
          this.chapterId = res.data.chapterId;
          this.kbId = res.data.kbId;
          this.questionKnowledge = this.kbId;
        });
    },

    // 切换题目类型
    handleChangeQuestionType(val) {
      switch (val) {
        case 1:
          this.$router.push({
            path: "/aiTeaching/courseBuild/makeAddChoiceQuestion",
            query: {},
          });
          break;
        case 2:
          this.$router.push({
            path: "/aiTeaching/courseBuild/makeAddJudgeQuestion",
            query: {},
          });
          break;
        case 3:
          this.$router.push({
            path: "/aiTeaching/courseBuild/makeAddFillBlankQuestion",
            query: {},
          });
          break;
        case 4:
          this.$router.push({
            path: "/aiTeaching/courseBuild/makeAddShortAnswerQuestion",
            query: {},
          });
          break;
        case 9:
          this.$router.push({
            path: "/aiTeaching/courseBuild/makeAddAnalysisQuestion",
            query: {},
          });
          break;

        default:
      }
    },

    // md转html - 题目编辑器
    onQuestionHtmlChanged(html) {
      this.questionContentHtml = html;
    },

    // md转html - 答案编辑器
    onCorrectAnswerHtmlChanged(html) {
      this.correctAnswerHtml = html;
    },

    // 保存题目
    saveQuestion() {
      // 验证表单
      if (!this.questionContent.trim()) {
        this.$message.warning("请输入试题题目");
        return;
      }

      if (!this.questionKnowledge) {
        this.$message.warning("请选择试题知识点");
        return;
      }

      if (!this.correctAnswer.trim()) {
        this.$message.warning("请输入试题答案");
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let queryObj = {};
      if (!this.questionId) {
        // 添加
        const selectedNode = this.$refs.questionKnowledge.getCheckedNodes();
        queryObj = {
          chapterId: selectedNode[0]?.data.parentId,
          kbId: selectedNode[0]?.data.value,
          questionType: 9,
          content: this.questionContent,
          htmlContent: this.questionContentHtml,
          answer: [
            {
              content: this.correctAnswer,
              htmlContent: this.correctAnswerHtml,
            },
          ],
        };
      } else {
        // 编辑
        const selectedNode = this.$refs.questionKnowledge.getCheckedNodes();
        queryObj = {
          id: this.questionId,
          chapterId: selectedNode[0]?.data.parentId,
          kbId: selectedNode[0]?.data.value,
          questionType: 9,
          content: this.questionContent,
          htmlContent: this.questionContentHtml,
          answer: [
            {
              content: this.correctAnswer,
              htmlContent: this.correctAnswerHtml,
            },
          ],
        };
      }

      const apiUrl = this.questionId
        ? `/tes/course/${this.courseId}/businessType/1/question-repository/question/${this.questionId}`
        : `/tes/course/${this.courseId}/businessType/1/question-repository/question`;

      const httpMethod = this.questionId ? "put" : "post";

      this.$axios[httpMethod](apiUrl, queryObj)
        .then((res) => {
          this.$message.success("保存成功！");
          // 清空表单数据
          this.questionContent = "";
          this.questionContentHtml = "";
          this.questionKnowledge = [];
          this.$router.push({
            path: "/aiTeaching/courseBuild/makeQuestionBank",
          });
        })
        .finally(() => {
          loading.close();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.add-judge-question {
  padding: 40px 50px 40px 70px;
  background-color: #fff;
  box-sizing: border-box;

  .form-group {
    margin-bottom: 30px;

    .form-label {
      display: block;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 15px;
    }

    .type-section-row {
      display: flex;
      gap: 40px;
      align-items: flex-start;

      .type-select-group,
      .section-select-group {
        display: flex;
        align-items: center;
        gap: 10px;

        .form-label {
          flex-shrink: 0;
          margin-bottom: 0;
        }

        .question-type-select,
        .question-section-select {
          :deep(.el-select__wrapper) {
            width: 180px;
            max-width: 300px;
          }
        }
      }
    }

    .editor-container {
      border: 1px solid #e0e0e0;
      border-radius: 4px;
    }

    .question-editor {
      height: 200px;
      :deep(.md-editor) {
        border: none;
      }
    }
  }

  .options-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .correct-answer-label {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      // margin-right: 60px;
    }
  }

  .options-container {
    .option-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 20px;
      gap: 15px;

      .option-label {
        width: 20px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 16px;
        color: #333;
        flex-shrink: 0;
      }

      .option-editor {
        flex: 1;
        border: 1px solid #e0e0e0;
        border-radius: 4px;

        .option-md-editor {
          height: 120px;
          :deep(.md-editor) {
            border: none;
          }
        }
      }

      .correct-answer-radio {
        width: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        // padding-top: 10px;
      }

      .option-delete {
        width: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        padding-top: 3px;

        .delete-option-btn {
          color: #999;
          padding: 4px;

          &:hover {
            color: #f56c6c;
          }

          .el-icon {
            font-size: 16px;
          }
        }
      }
    }
  }

  .add-option-container {
    margin-bottom: 30px;
    display: flex;
    align-items: center;
    gap: 15px;

    .option-label-placeholder {
      width: 20px;
      flex-shrink: 0;
    }

    .correct-answer-placeholder {
      width: 60px;
      flex-shrink: 0;
    }

    .delete-placeholder {
      width: 40px;
      flex-shrink: 0;
    }

    .add-option-btn {
      flex: 1;
      height: 50px;
      border: 2px dashed #ddd;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #457aff;
        color: #457aff;
      }

      .el-icon {
        color: #457aff;
        font-size: 20px;
      }
    }
  }

  .save-container {
    text-align: center;
    margin-top: 40px;
    margin-right: 90px;

    .save-btn {
      padding: 12px 30px;
      font-size: 16px;
    }
  }
}

// 全局样式调整
:deep(.md-editor) {
  --md-color: #333;
  --md-hover-color: #155eef;
  --md-bk-color: #fff;
  --md-border-color: #e0e0e0;
  .md-editor-footer {
    display: none;
  }
}
</style>